/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
  ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {

    ListNode *p1 = headA;
    ListNode *p2 = headB;
    int n1 = 0;
    int n2 = 0;

    // 分别测算两个链表的长度及其差值
    while(p1){
      p1 = p1->next;
      ++n1;
    }
    while(p2){
      p2 = p2->next;
      ++n2;
    }
    int k = abs(n1 - n2);

    p1 = headA;
    p2 = headB;

    // 总是让p1指向较长的那个链表
    if(n1 < n2){
      swap(p1, p2);
    }

    // 让较长的那个链表先走k步
    while(k--){
      p1 = p1->next;
    }

    // 再同步遍历
    while(p1 && p2){
      if(p1 == p2){
        break;
      }
      p1 = p1->next;
      p2 = p2->next;
    }

    return p1;

  }
};